package com.hut.oa.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hut.oa.model.bean.AttendComplaint;
import com.hut.oa.model.bean.User;
import com.hut.oa.model.bean.WorkAttend;
import com.hut.oa.model.dao.user.DeptDao;
import com.hut.oa.model.dao.user.UserDao;
import com.hut.oa.model.dao.workattend.AttendComplaintDao;
import com.hut.oa.model.dao.workattend.WorkAttendDao;

@Controller
@RequestMapping("/work/attend")
public class WorkAttendController {
	
	@Autowired
	DeptDao dd;
	
	@Autowired
	WorkAttendDao wad;

	@Autowired
	AttendComplaintDao acd;

	@Autowired
	UserDao ud;
	
	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
	SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**
	 * 考勤报表
	 * 
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping("/check")
	public String check(HttpSession session,HttpServletRequest req,Model model, @PageableDefault(value = 10, sort = { "id" }) Pageable pageable) throws ParseException {
		
		/*, @RequestParam(name = "key") String key,
		@RequestParam(name = "did") String did, @RequestParam(name = "start") String start,
		@RequestParam(name = "end")String end,*/
		String key=req.getParameter("key");
		String did=req.getParameter("did");
		String start=req.getParameter("start");
		String end=req.getParameter("end");
		String ths=req.getParameter("ths");
		model.addAttribute("ths", ths);
		User uswe=(User)session.getAttribute("userinfo");
		Date now1=new Date();
		Date st=new Date();
		st.setDate(01);
		now1.setDate(01);
		Date now2=new Date();
		Date e=new Date();
		if (start!=null) {
			System.out.println(start+"sss"+end);
			now1=sdf.parse(start);
			now2=sdf.parse(end);
			st=sdf.parse(start);
			e=sdf.parse(end);
		}
		Page<User> users = ud.findAll(pageable);
		if (key!=null) {
			if (did!=null) {
				users = ud.findByRealNameAndDept(key, dd.findOne(Long.parseLong(did)), pageable);
			}else{
				users = ud.findByRealNameLikeLike(key, pageable);
			}
		}
		List<User> us = users.getContent();
		List<Map<String, Object>> check = new ArrayList<>();
		List<WorkAttend> wa = wad.findbytime(now1, now2);
		model.addAttribute("start", now1);
		model.addAttribute("end", now2);
		
		int dates = getDutyDays(st,e);
		System.out.println(wa);
		for (User user : us) {
			Map<String, Object> s = new HashMap<>();
			s.put("name", user.getRealName());
			// 工作日数目

			// 统计正常签到次数
			int sign = 0;
			for (WorkAttend workAttend : wa) {
				if (workAttend.getUser().getId() == user.getId() && workAttend.getStatus().equals(0)
						&& workAttend.getType().equals("签到")) {
					sign += 1;
				}
			}
			s.put("sign", sign);
			// 统计迟到次数
			int late = 0;
			for (WorkAttend workAttend : wa) {
				if (workAttend.getUser().getId() == user.getId() && workAttend.getStatus().equals(1)
						&& workAttend.getType().equals("签到")) {
					late += 1;
				}
			}
			s.put("late", late);
			//总签到
			s.put("szon", sign+late);
			//还需签到
			s.put("si", uswe.getDept().getCheckDay()-sign-late);
			//未签到次数
			s.put("signno", dates-sign-late);
			// 统计正常签退次数
			int signOut = 0;
			for (WorkAttend workAttend : wa) {
				if (workAttend.getUser().getId() == user.getId() && workAttend.getStatus().equals(0)
						&& workAttend.getType().equals("签退")) {
					signOut += 1;
				}
			}
			s.put("signOut", signOut);
			// 统计早退次数
			int leaveEarly = 0;
			for (WorkAttend workAttend : wa) {
				if (workAttend.getUser().getId() == user.getId() && workAttend.getStatus().equals(3)
						&& workAttend.getType().equals("签退")) {
					leaveEarly += 1;
				}
			}
			s.put("leaveEarly", leaveEarly);
			//未签退次数
			s.put("signOutno", dates-signOut-leaveEarly);
			s.put("zongt", signOut+leaveEarly);
			//还需签退
			s.put("tuis",uswe.getDept().getCheckDay()-signOut-leaveEarly);
			// 统计请假次数
			int jia = 0;
			for (WorkAttend workAttend : wa) {
				if (workAttend.getUser().getId() == user.getId() && workAttend.getType().equals("请假")) {
					System.out.println(workAttend);
					jia += 1;
				}
			}
			s.put("jia", jia);
			// 统计迟到次数
			check.add(s);
		}
		
		model.addAttribute("check", check);
		model.addAttribute("users", users);
		model.addAttribute("depts", dd.findAllByOrderByGrade());
		return "work_attend/check";
	}

	/**
	 * 我的考勤
	 * 
	 * @param model
	 * @param session
	 * @param pageable
	 * @return
	 */
	@RequestMapping("/my")
	public String my(Model model, HttpSession session,
			@PageableDefault(value = 5, sort = { "id" }, direction = Direction.DESC) Pageable pageable) {
		User user = (User) session.getAttribute("userinfo");
		model.addAttribute("go", wad.finByuidtypeto("签到", user.getId()));
		model.addAttribute("out", wad.finByuidtypeto("签退", user.getId()));
		model.addAttribute("jia", wad.finByuidtypeto("请假", user.getId()));
		model.addAttribute("wa", wad.findByUser(user, pageable));
		return "work_attend/my_work_attend";
	}

	/**
	 * 申诉管理
	 */
	@RequestMapping("/complaints")
	public String complaints(Model model,String name,Integer st,
			@PageableDefault(value = 10, sort = "time",direction=Direction.DESC) Pageable pageable) {
		// User user=(User)session.getAttribute("userinfo");
		System.out.println(name+"aa:"+st+"==============");
		if (name==null) {
			model.addAttribute("st", 0);
			model.addAttribute("complaint", acd.finbynameandst("", 0, pageable));
		}else if (st==null) {
			model.addAttribute("complaint", acd.finbyname(name, pageable));
		}else{
			model.addAttribute("complaint", acd.finbynameandst(name, st, pageable));
		}
		return "work_attend/work_complaint";
	}

	/**
	 * 添加或修改打卡记录
	 */
	@ResponseBody
	@RequestMapping("/save")
	public WorkAttend seav(WorkAttend wa, HttpSession session) {
		User user = (User) session.getAttribute("userinfo");
		wa.setUser(user);
		Integer status = wa.getStatus();
		if (wa.getId() != null) {
			wa = wad.findOne(wa.getId());
			wa.setTime(new Date());
			wa.setStatus(status);
		}
		return wad.save(wa);
	}

	/**
	 * 异常打卡申诉
	 * @throws ParseException 
	 */
	@ResponseBody
	@RequestMapping("/complaint")
	public Boolean complaint(AttendComplaint ac,@RequestParam("ip")String ip, @RequestParam("aid")Long aid,HttpSession session) throws ParseException {
		User user=(User)session.getAttribute("userinfo");
		if (aid!=0) {
			ac.setWorkattend(wad.findOne(aid));
		}else {
			WorkAttend waw=new WorkAttend();
			waw.setType("");
			String time=ac.getReason().substring(0,10);
			String type=ac.getReason().substring(15,17);
			waw.setUser(user);
			Date ti=sdf2.parse(time+" "+user.getDept().getBeginTime());
			waw.setTime(ti);
			waw.setIp(ip);
			waw.setRemark("无申诉");
			if (type.equals("缺勤")) {
				waw.setType("签到");
				waw.setStatus(3);
			}else {
				waw.setType("签退");
				waw.setStatus(4);
			}
			WorkAttend waws=wad.save(waw);
			aid=waws.getId();
			ac.setWorkattend(waws);
		}
		
		if (acd.save(ac) != null) {
			WorkAttend wa = wad.findOne(aid);
			wa.setRemark("申诉待处理");
			wad.save(wa);
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 异常打卡重新申诉
	 */
	@ResponseBody
	@RequestMapping("/complainttwe")
	public Boolean complaint2(AttendComplaint ac) {
		AttendComplaint ac2=acd.findOne(ac.getId());
		ac2.setContent(ac.getContent());
		ac2.setState(0);
		ac2.setTime(new Date());
		if (acd.save(ac2) != null) {
			WorkAttend wa = wad.findOne(ac2.getWorkattend().getId());
			wa.setRemark("申诉待处理");
			wad.save(wa);
			return true;
		} else {
			return false;
		}

	}
	/**
	 * 异常打卡申诉处理
	 */
	@ResponseBody
	@RequestMapping("/com")
	public Boolean com(AttendComplaint ac,HttpSession session) {
		User user=(User)session.getAttribute("userinfo");
		AttendComplaint ac2 = acd.findOne(ac.getId());
		if (ac2.getWorkattend().getStatus()==5) {
			acd.delete(ac2);
			return true;
		}
		ac2.setState(ac.getState());
		ac2.setResult(ac.getResult());
		ac2.setUser(user);
		if (acd.save(ac2) != null) {
			// 判断是否是同意申诉
			if (ac.getState() == 1) {
				WorkAttend wa = ac2.getWorkattend();
				wa.setStatus(0);
				wa.setRemark("申诉已同意");
				wad.save(wa);
			}else{
				WorkAttend wa = ac2.getWorkattend();
				wa.setRemark("申诉已退回");
				wad.save(wa);
			}
			return true;
		} else {
			return false;
		}

	}
	/**
	 * 返回当前用户打卡记录或通过id
	 * 
	 */
	@ResponseBody
	@RequestMapping("/mywa")
	public List<WorkAttend> mywa(String uid, HttpSession session) {
		User user=(User) session.getAttribute("userinfo");
		if (uid!=null&&!uid.equals("null")) {
			user = ud.findById(Long.parseLong(uid+""));
		}
		List<WorkAttend> was=wad.findByUser(user);
		return was;
	}
	/**
	 * 通知多人
	 */
	@ResponseBody
	@RequestMapping("/annusers")
	public Boolean annusers(String con,HttpServletRequest req) {
		String us=req.getParameter("users");
		String[] users=us.split(",");
		System.out.println(users);
		System.out.println(con);
		return true;
	}
	/**
	 * 通过id查询某条申诉记录
	 * @param model
	 * @param session
	 * @param pageable
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/bywaid")
	public AttendComplaint fbyidwa(@RequestParam(name="id")Long id) {
		AttendComplaint ac=acd.findOne(id);
		return ac;
	}
	/**
	 * 两个日期之间天数（除去双休）
	 */
	private int getDutyDays(Date startDate, Date endDate) {
		int result = 0;
		while (startDate.compareTo(endDate) <= 0) {
			if (startDate.getDay() != 6 && startDate.getDay() != 0)
				result++;
			startDate.setDate(startDate.getDate() + 1);
		}
		return result;
	}
}
